var abs = new verjs_select();

$(function () {
    getProvince();
    getCity('110000');
    $('#search').css('display', 'none');
    $('#companyLabel').css('display', 'none');
    $('#companyDiv').css('display', 'none');
    $('#timeLimitLabel').css('display', 'none');
    $('#timeLimitDiv').css('display', 'none');
    loadCompanyListData();
    loadCompanySelect();
});

// 渲染城市列表
function getProvince() {
    let provinceNames = [];
    $.each(cityJson[0], function (key, value) {
        provinceNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#province').html(provinceNames.join(''));
    //getCity('110000');
}

// 根据省获取市
function getCity(provinceId) {
    $('#city').html('');
    let key = '0,' + provinceId;
    let cityNames = [];
    $.each(cityJson[key], function (key, value) {
        cityNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#city').html(cityNames.join(''));
}

// '切换城市'
function changeCity() {
    getCity($('#province').val())
}

// 池子
function seleceChi(type) {
    if (type == 2 ) {
        $('#search').css('display', 'inline-block');
        $('#companyLabel').css('display', 'none');
        $('#companyDiv').css('display', 'none');
        $('#timeLimitLabel').css('display', 'none');
        $('#timeLimitDiv').css('display', 'none');
    } else {
        $('#search').css('display', 'none');
        $('#companyLabel').css('display', 'block');
        $('#companyDiv').css('display', 'block');
        $('#timeLimitLabel').css('display', 'block');
        $('#timeLimitDiv').css('display', 'flex');
    }
}

/**
 * 加载公司列表
 */
function loadCompanyListData() {
    $.ajax({
        url: "/company/getCompanyList",
        type: 'GET',
        datatype: 'json',
        success: function (data) {
            if (data) {
                if (data.code == '000000') {
                    var selectDate = [];
                    for (var i = 0, len = data.data.length; i < len; i++) {
                        var company = data.data[i];
                        var selectCompany = {};
                        selectCompany.id = company.companyId;
                        selectCompany.name = company.companyName;
                        selectDate.push(selectCompany);
                    }
                    abs.render({
                        elem: "#search",
                        data: selectDate,
                        init_value: [1],
                        body_height: 300,
                        checkbox: true,
                        name: "test"
                    });
                    $('#searchoption-list').css('z-index',1000);
                } else {
                    $.alert("查询所有公司失败");
                }

            }
        },
        error: function () {
            $.alert('查询所有公司异常');
        }
    });
}

/**
 * 加载全国池关联公司下拉列表
 */
function loadCompanySelect() {
    $.getJSON("/company/getCompanyList", function (data) {
        if (data.code == '000000') {
            var companyOptionHtml = '<option value="">请选择所属公司</option>';
            data.data.map(function (item) {
                companyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $("#companySelect").html("");
            $('#companySelect').append(companyOptionHtml);
            $('#companySelect').selectpicker('refresh');
        }
    });
}

/**
 * 新增客户池
 */
function addCustomerPool(){
    //客户池名称
    var customerPoolName = $.trim($("#customerPoolName").val());

    //来源
    var source = $.trim($("#source").val());

    //省份id
    var provinceId = $('#province').val();

    //省份名称
    var provinceName = $("#province").find("option:selected").text();

    //城市id
    var cityId = $('#city').val();

    //城市名称
    var cityName = $("#city").find("option:selected").text();

    //行业
    var industry =  $("#industry").val();

    //客户池类型
    var poolType = $('#poolType').val();

    //客户池容量
    var capacity = $("#capacity").val();

    var tagStr = $('.fm-button').text().split(' ').join(',');
    var tagStrNew = tagStr.substring(0, tagStr.lastIndexOf(','))+ tagStr.substring(tagStr.lastIndexOf(',')+1);
    //客户池标签
    var tag = tagStrNew;

    //性质
    var nature = $("input[name='nature']:checked").val();

    //公司id
    var selectCompany = [];
    selectCompany = abs.get_value('search');
    var companyIdList = [];
    for(let i=0;i<selectCompany.length;i++) {
        companyIdList.push(selectCompany[i].id);
    }

    //无跟进退回时间间隔
    var returnInterval = $("#returnInterval").val();

    //最多领取数量
    var maximumNumber = $("#maximumNumber").val();

    //同一客户不能连续领取间隔
    var timeInterval = $("#timeInterval").val();

    //任意客户不能连续领取间隔
    var anyTimeInterval = $("#anyTimeInterval").val();

    //全国公有池 所属公司
    var affiliatedCompanyId = $("#companySelect").val();

    //其它公司时间限制
    var timeLimit = $("#timeLimit").val();

    //客户池名称为空和长度验证
    if (!customerPoolName) {
        $.alert("客户池名称不能为空!");
        return;
    } else {
        if (customerPoolName.length > 50) {
            $.alert("客户池名称长度不能大于50个字符！");
            return;
        }
    }

    //所在行业
    if (!industry) {
        $.alert("所在行业不能为空!");
        return;
    }

    //标签为空判断
    if(!tag){
        $.alert("标签不能为空！");
        return;
    }

    //客户池容量判断
    if(!capacity){
        $.alert("客户池容量不能为空！");
        return;
    }

    //客户池性质
    if(!nature){
        $.alert("客户池性质必选！");
        return;
    }
    if (nature == 2) {
        if(companyIdList.length == 0){
            $.alert("分公司必选！");
            return;
        }
    }

    //最多领取数量
    if(!maximumNumber){
        $.alert("最多领取数量必填！");
        return;
    }

    //同一客户不能连续领取间隔
    if(!timeInterval){
        $.alert("同一客户不能连续领取间隔必填！");
        return;
    }

    //任意客户不能连续领取间隔
    if(!anyTimeInterval){
        $.alert("任意客户不能连续领取间隔必填！");
        return;
    }

    //无跟进时间间隔验证
    if(!returnInterval){
        $.alert("无跟进退回时间间隔必填！");
        return;
    }

    var jsonData = {
        "customerPoolName":customerPoolName,
        "source":source,
        "provinceId":provinceId,
        "provinceName":provinceName,
        "cityId":cityId,
        "cityName":cityName,
        "industry":industry,
        "poolType":poolType,
        "capacity":capacity,
        "tag":tag,
        "nature":nature,
        "companyIdList":companyIdList,
        "returnInterval":returnInterval,
        "maximumNumber":maximumNumber,
        "timeInterval":timeInterval,
        "anyTimeInterval":anyTimeInterval,
        "affiliatedCompanyId":affiliatedCompanyId,
        "timeLimit":timeLimit
    };
    $.ajax({
        url: '/customer/addCustomerPool',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                var navTab = parent.$multitabs._getNavTab($thisTabs);
                                closeTab(navTab);
                                openTab("客户公海","/front/customerManager/customerPoolForm");
                                // 提交完表单，重新加载相关table列表页面
                                refreshActivePane('/front/customerManager/customerPoolForm');

                                delStorageAndRemove(navTab);
                            }
                        }
                    }
                });
            } else if(data.code == "CP0000"){
                $.alert(data.message);
            } else {
                $.alert("保存失败");
            }
        }),
        error: (function (res) {
            $.alert("保存异常");
        })
    });

}

function cancelAddCustomerPool(){
    window.location.reload();
}